package com.cas.listener;

import com.cas.service.TriggerLogoutService;
import com.cas.service.UserService;
import org.apereo.cas.support.events.ticket.CasTicketGrantingTicketCreatedEvent;
import org.apereo.cas.ticket.TicketGrantingTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 单用户登录
 * 第一步
 * TGT创建监听
 * @author Leighton
 * @create 2018-11-14.
 * 这个监听是为了用户登录成功后对其他用户进行剔除
 */
public class TGTCreateEventListener {
    private TriggerLogoutService logoutService;

    @Autowired
    private UserService userService;

    public TGTCreateEventListener( @NotNull TriggerLogoutService logoutService) {
        this.logoutService = logoutService;
    }

    @EventListener
    @Async
    public void onTgtCreateEvent(CasTicketGrantingTicketCreatedEvent event) {
        // 监听tgt创建事件
        TicketGrantingTicket ticketGrantingTicket = event.getTicketGrantingTicket();
        //2. 获取用户id，以及tgt
        String id = ticketGrantingTicket.getAuthentication().getPrincipal().getId();
        String tgt=ticketGrantingTicket.getId();

        //3. 根据用户id，认证方式clientName寻找所有的tgt
        String clientName = (String) ticketGrantingTicket.getAuthentication().getAttributes().get("clientName");
        //获取可以认证的id
        List<String> authIds = userService.obtain(clientName, id);
        if (authIds != null) {
            //循环触发登出 5. 删除过滤后的tgt（正确的逻辑过滤后一般情况剩下一个，因为已经单用户登录了）
            authIds.forEach(authId -> logoutService.triggerLogout(authId, tgt));
        }

    }
}
